package jdk5.generics;

import java.util.ArrayList;
import java.util.List;

public class GenericsGrammar {
    public static void main(String[] args) {

        // 参数化的类
        SimpleList<Integer, String> simpleList = new SimpleList<Integer, String>();
        //simpleList.add("dsf");
        simpleList.add(Integer.valueOf(1231));
        simpleList.addT("sdfljs");

        // enum 类型
        System.out.println(Gender.FEMALE);
        System.out.println(Gender.FEMALE.getDisplayName());

    }

    // 泛型方法, 无需参数化类, 直接参数化类
    public <E> String formatArray(E[] arrayToFormat) {
        StringBuilder builder = new StringBuilder();

        int index = 0;
        for (E e : arrayToFormat) {
            builder.append("Element");
            builder.append(index);
            builder.append(" => ");
            builder.append("\n");
        }

        return builder.toString();
    }

    // 泛型迭代
    public static void genericsIterable() {
        // 迭代泛型

        // 没有泛型之前:
        List list1 = new ArrayList();
        list1.add("sdfds");
        list1.add(new Integer("12"));
//        for (String str : list1) {  }

        // 引入泛型后
        List<String> list = new ArrayList<>();
        list.add("qew");
        list.add("dskflj");
        for (String str : list) {
            System.out.println(str);
        }
    }

}

// 参数化的类
class SimpleList<E, T> {
    private List<E> backingStore;

    public SimpleList() {
        this.backingStore = new ArrayList<E>();
    }

    public E add(E e) {
        if (backingStore.add(e)) {
            return e;
        } else {
            return null;
        }
    }

    public T addT(T t) {
        System.out.println(t);
        return t;
    }

    public int size() {
        return backingStore.size();
    }

    public void clear() {
        backingStore.clear();
    }
}


// enum 类型

enum Gender {
    MALE("male"),
    FEMALE("female"),
    OTHER("other");

    // 构造方法 : 只允许声明为private
    private String displayName;

    Gender(String displayName) {
        this.displayName = displayName;
    }

    public String getDisplayName() {
        return displayName;
    }
}

// enum 类型也可以实现接口
interface DisplayName {
    public String getDispalyName();
}

enum Gender2 implements DisplayName {
    MALE("male"),
    FEMALE("female")
    ;

    private String dispalyName;

    Gender2(String dispalyName) {
        this.dispalyName = dispalyName;
    }

    @Override
    public String getDispalyName() {
        return this.dispalyName;
    }
}